import { Square } from "./Square";
import { Point, Shape } from "./types";
import { SquarePageViewer } from "./viewer/SquarePageViewer";
import $ from "jquery";

/**
 * 组合方块
 * 1. 小方块列表: 相对坐标数组
 * 2. 方块颜色
 * 3. 中心小方块的坐标(3,5)
 */
export abstract class SquareGroup {
  private _squares: readonly Square[] = [];

  constructor(private _shape: Shape, private _centerPoint: Point, private _color: string) {
    // 根据相对坐标 + 中心小方块真实坐标，生成小方块
    this._squares = this._shape.map(p => {
      const x = p.x + this._centerPoint.x;
      const y = p.y + this._centerPoint.y;
      const sq = new Square({ x, y }, this._color);
      return sq;
    });
  }

  public get squares() {
    return this._squares;
  }

  public get shape() {
    return this._shape;
  }

  public get centerPoint() {
    return this._centerPoint;
  }

  public get color() {
    return this._color;
  }

  public set centerPoint(v: Point) {
    this._centerPoint = v;
    // 中心点改变时，其他方块位置也改变
    this.setSquarePoint();
  }

  protected isClock = true; // 旋转方向：默认为顺时针
  /**
   * 旋转：根据当前形状产生一个新的形状
   */
  rotate() {
    const newShape = this.afterRotateShape();
    this._shape = newShape;
    this.setSquarePoint();
  }

  /**
   * 旋转：根据当前形状产生一个新的形状
   */
  afterRotateShape(): Shape {
    if (this.isClock) {
      return this._shape.map(p => ({ x: -p.y, y: p.x } as Point));
    } else {
      return this._shape.map(p => ({ y: -p.x, x: p.y } as Point));
    }
  }

  setSquarePoint() {
    // 旋转后，其他方块位置也改变
    this._shape.forEach((p, i) => {
      this._squares[i].point = {
        x: this._centerPoint.x + p.x,
        y: this._centerPoint.y + p.y
      };
    });
  }
}
